package core;

import javafx.application.Platform;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.scene.control.TextArea;
import util.FileUtil;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * 解压文件核心逻辑
 *
 * @author xiaopu
 */
public class UnZip{



    /**
     * @param sourcePath 源路径
     * @param targetPath 目标路径
     * @throws IOException io异常
     */
    public void unZipFile(String sourcePath, String targetPath, TextArea log) throws IOException, InterruptedException {
        if (sourcePath == null || "".equalsIgnoreCase(sourcePath)) {
            return;
        }
        ArrayList<File> deleteFolders = new ArrayList<>();
        File file = new File(sourcePath);
        //文件
        if (file.isFile()) {
            //是否压缩文件
            boolean isZip = FileUtil.determineTheSuffixName(file.getAbsolutePath(), "zip");
            if (isZip) {
                ZipFile zipFile = new ZipFile(file.getAbsoluteFile(), Charset.forName("GBK"));
                Enumeration<? extends ZipEntry> entries = zipFile.entries();
                while (entries.hasMoreElements()) {
                    ZipEntry entry = entries.nextElement();
                    //压缩项是文件夹
                    if (entry.isDirectory()) {
                        File folder = new File(targetPath + File.separator + entry.getName());
                        if (!folder.exists()) {
                            boolean mkdirs = folder.mkdirs();
                            if (mkdirs) {
                                deleteFolders.add(folder);
                            }
                        }
                    } else {
                        InputStream zipIn = new BufferedInputStream(zipFile.getInputStream(entry));
                        File outFile = new File(targetPath + File.separator + entry.getName());
                        OutputStream zipOut = new BufferedOutputStream(new FileOutputStream(outFile));
                        if (!outFile.exists()) {
                            boolean newFile = outFile.createNewFile();
                        }
                        String outPath = outFile.getAbsolutePath();
                        // System.out.println("解压文件：" + outPath);
                        Platform.runLater(() -> {
                            log.appendText("解压文件：" + outPath + '\n');
                        });
                        int pos = 0;
                        byte[] bytes = new byte[1024 * 3];
                        while ((pos = zipIn.read(bytes)) != -1) {
                            zipOut.write(bytes, 0, pos);
                        }
                        zipOut.close();
                        zipIn.close();
                        //如果解压出来的还是压缩包，继续向里解压
                        if (FileUtil.determineTheSuffixName(outPath, "zip")) {
                            unZipFile(outPath, targetPath, log);
                            //里层解压完毕，删除解压出来的压缩包
                            File tempZip = new File(outPath);
                            if (tempZip.isFile() && tempZip.exists()) {
                                FileUtil.determineTheSuffixName(tempZip.getAbsolutePath(), "zip");
                                boolean delete = tempZip.delete();
                            }
                        }
                    }
                }
                zipFile.close();
            }
            //是否指定后缀的非压缩文件

        } else if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null && files.length > 0) {
                for (File file1 : files) {
                    unZipFile(file1.getAbsolutePath(), targetPath, log);
                }
            }
        }
        for (File deleteFolder : deleteFolders) {
            if (deleteFolder.exists()) {
                boolean delete = deleteFolder.delete();
            }
        }
    }


}
